{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#Numpy使用ndarray对象（数组）来处理多维数组",
   "id": "9f1e1eff67e2d2a1"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-09T03:47:11.681689Z",
     "start_time": "2025-01-09T03:47:11.594429Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "import time\n",
    "import random"
   ],
   "id": "initial_id",
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#创建数组     np.array()      np.arange()",
   "id": "cd6010e74acbe42a"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "#创建一维数组\n",
    "my_list=[0,1,2,3,4]\n",
    "my_array=np.array(my_list)#将列表转化为数组\n",
    "print(type(my_array))\n",
    "print(my_array)\n",
    "my_array=np.array(range(5))#将range函数生成序列转化为数组\n",
    "print(type(my_array))\n",
    "print(my_array)\n",
    "my_array=np.arange(5)#使用numpy的arange（）函数创建数组\n",
    "print(type(my_array))\n",
    "print(my_array)\n",
    "#创建二维数组\n",
    "my_list=[[1,2,3],[4,5,6]]\n",
    "my_array=np.array(my_list)#将二维列表转化为二维数组\n",
    "print(type(my_array))\n",
    "print(my_array)\n",
    "#另外将数组转成列表\n",
    "my_list=my_array.tolist()#使用tolist()方法将数组转化为列表\n",
    "print(type(my_list))"
   ],
   "id": "2b39d3e53aaf4a5f",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#数组的属性",
   "id": "b3dc553d6ec49e69"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "print(my_array.ndim)#维度\n",
    "print(my_array.shape)#形状(行数，列数)\n",
    "print(my_array.size)#元素个数\n",
    "print(my_array.dtype)#数据类型(ndarray中元素的类型:ndarray中的所有元素必须是相同的数据类型)"
   ],
   "id": "f8029ac51bb89d3",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#调整数组属性：形状、维度",
   "id": "4503f5cb42498e60"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "#调整多维数组形状\n",
    "print(my_array)\n",
    "my_array.shape=(3,2)#修改原数组的形状\n",
    "print(my_array)\n",
    "new_array=my_array.reshape(2,3)#原数组形状不变，返回一个新的数组\n",
    "print(new_array)\n",
    "#多维转一维\n",
    "new_array=my_array.reshape(6,)#多维数组转为一维数组。注意区别于new_array=my_array.reshape(1,6)这个还是二维数组（1行6列）。\n",
    "print(new_array.ndim)\n",
    "new_array=my_array.reshape(-1)#可以使用-1作为参数，numpy会自动计算合适的尺寸。\n",
    "print(new_array.ndim)\n",
    "new_array=my_array.flatten()#使用flatten方法铺平数组\n",
    "print(new_array.ndim)\n",
    "#一维转多维\n",
    "print(new_array.reshape(2,3))#一维数组转化为多维数组"
   ],
   "id": "5f9b76f59cc0794b",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#调整数组属性：数据类型",
   "id": "b7fe69383e1cf94f"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "print(my_array.itemsize)#返回数组中每个元素的字节长度\n",
    "print(my_array.dtype)#获取数据类型\n",
    "temp_array=np.array([1,2,3,4,5],dtype=np.int16)#创建数据时可指定数据类型（利用np.数据类型传给dtype参数）\n",
    "print(temp_array.itemsize)\n",
    "print(temp_array.dtype)\n",
    "temp_array=new_array.astype(np.float32)#调整数组类型后返回（利用数组的astype方法）\n",
    "print(temp_array.itemsize)\n",
    "print(temp_array.dtype)\n",
    "#另外当数据类型是浮点数时\n",
    "temp_array=np.array([random.random() for i in range(5)])#random.random()表示随机生成0-1之间的小数\n",
    "print(temp_array)\n",
    "temp_array=np.round(temp_array,2)#通过np.round函数指定元素保留两位小数后返回\n",
    "print(temp_array)"
   ],
   "id": "69129cd84580b64c",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#数组和数的计算：加减乘除的值被广播到所有的元素上面",
   "id": "7eb680372f1fe3e9"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "array1=np.arange(6).reshape(2,3)\n",
    "print(array1)\n",
    "print(array1+10)\n",
    "print(array1*2)\n",
    "print(array1/2)"
   ],
   "id": "50b4d93a7fceac3e",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#数组与数组的计算",
   "id": "e7b326eb6c71821f"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "#同种形状的数组:对应位置进行计算，不同形状的多维数组一般不能计算。\n",
    "array1=np.arange(6).reshape(2,3)\n",
    "array2=np.arange(6,12).reshape(2,3)\n",
    "print(array1+array2)\n",
    "print(array1*array2)\n",
    "#一维数组和多维数组的计算:一维数组的元素个数须与多维数组最内轴的元素个数相同，实现在最内轴上的广播计算（一维数组的元素分别与各内轴对应位置元素相计算）\n",
    "array2=np.array([0,2,4])\n",
    "print(array1+array2)\n",
    "array1=np.arange(24).reshape((2, 3, 4))\n",
    "array2=np.array([0,1,2,3])\n",
    "print(array1+array2)\n",
    "#不同形状的多维数组要计算需：1、维度相同2、只有一轴形状不同且其中一个数组在这一轴上为1,实现在这一轴上的广播计算\n",
    "array1=np.arange(12).reshape((2, 2, 3))\n",
    "array2=np.arange(6).reshape((1, 2, 3))\n",
    "print(array1)\n",
    "print(array1-array2)"
   ],
   "id": "618c462311ca3872",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#练习函数",
   "id": "2fa78fbdc69c105e"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "array1=np.arange(12).reshape((2, 2, 3))\n",
    "print(array1)\n",
    "#求和np.sum()\n",
    "array2=np.sum(array1,axis=0)#指定数组某轴（通过axis参数）求和：沿着哪轴求和哪轴的元素加和为一个相应元素然后轴消失\n",
    "print(array2.shape)\n",
    "print(array2)\n",
    "print(np.sum(array1))#数组所有元素求和\n",
    "#求平均值np.mean()\n",
    "print(np.mean(array1,axis=0))#指定数组某轴（通过axis参数）求平均数：沿着哪轴求平均数哪轴的元素求出平均数后然后轴消失\n",
    "print(np.mean(array1))#数组所有元素求平均数\n",
    "#求最大值np.max()\n",
    "print(np.max(array1,axis=0))#同理\n",
    "print(np.max(array1))#同理\n",
    "#求最小值np.min()\n",
    "print(np.min(array1,axis=0))#同理 \n",
    "print(np.min(array1))#同理"
   ],
   "id": "4c45d5826a7fa870",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#通过索引切片：规则【1,用来分隔各轴的切片方式，轴0在前面然后依次排】【2：用来分隔此轴的切片参数start:stop:step各轴索引号从0开始】【3start闭stop开即左闭右开】",
   "id": "672ee5c90e28e65d"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "array1=np.arange(12).reshape(3, 4)\n",
    "print(array1)\n",
    "#切连续的\n",
    "print(array1[1:3,0:3])#切行数（轴0）1到2，切列数（轴1）0到2\n",
    "print(array1[1:3])#省略列数切片就全切\n",
    "print(array1[:,0:3])#省略行数切片的写法\n",
    "print(array1[1:,0:3])#某轴省略stop参数就一直切到这轴最后，若切片参数全省略表全切\n",
    "#切不连续的\n",
    "print(array1[1])#切第1行等价于print(array1[1,：])\n",
    "print(array1[:,[0,3]])#切不连续的列0和3\n",
    "print(array1[[0,2],[0,3]])#这个表示切出0行0列的元素和2行3列的元素\n",
    "print(array1[[0, 2]][:, [0, 3]])#这个切0、2列和0、3行（前面的[[0, 2]]表示切0、2行，后面的[:, [0, 3]]表示在前面的基础上再切0、3列）。"
   ],
   "id": "365686cfb5447819",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#修改数组中的元素",
   "id": "25112e5d2e9b6f86"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-09T03:53:23.835104Z",
     "start_time": "2025-01-09T03:53:23.828838Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#通过索引修改\n",
    "array1=np.arange(12).reshape(3, 4)\n",
    "print(array1)\n",
    "array1[1,:]=0#将第1行的元素全部改为0\n",
    "print(array1)\n",
    "#设置条件修改\n",
    "array1[(array1<3) | (array1>9)]=0#这里的逻辑运算符号：|表示或，&表示与，~表示非\n",
    "print(array1)"
   ],
   "id": "946848714ddb903b",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  1  2  3]\n",
      " [ 4  5  6  7]\n",
      " [ 8  9 10 11]]\n",
      "[[ 0  1  2  3]\n",
      " [ 0  0  0  0]\n",
      " [ 8  9 10 11]]\n",
      "[[0 0 0 3]\n",
      " [0 0 0 0]\n",
      " [8 9 0 0]]\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#nan（表示缺失数据）和inf（表示无穷）",
   "id": "a0428fef6d6d669c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-09T05:12:58.559564Z",
     "start_time": "2025-01-09T05:12:58.553880Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#创建\n",
    "a=np.nan\n",
    "b=np.inf\n",
    "print(type(a))#nan是浮点数类型,inf也是浮点数类型\n",
    "#运算\n",
    "print(a==b)#nan不等于nan\n",
    "print(a+1)#nan和其他数运算的结果都是nan\n",
    "#统计数组中nan的数量：利用nan！=nan的特点通过数组运算得到对应布尔数组，布尔数组中为False的位置即原为nan，然后根据False的值为1，统计布尔数组中非0的个数即为nan的个数\n",
    "array1=np.arange(12).reshape(3,4)\n",
    "print(array1)\n",
    "array1=array1.astype(np.float32)#将数组的数据类型转化为浮点数，这样nan才可能写入\n",
    "array1[[0,0,1],[0,2,3]]=np.nan#往数组中写入3个nan\n",
    "bool_array1=array1 != array1#返回一个布尔数组，元素为False表示对应元素是nan\n",
    "print(np.count_nonzero(bool_array1))#用np.count_nonzero() 来统计非零元素的个数\n",
    "array1[np.isnan(array1)] = 99#用np.isnan()来判断元素是否为nan，然后用布尔数组来修改原为nan的值\n",
    "print(array1)"
   ],
   "id": "8fa28a5779285d38",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'float'>\n",
      "False\n",
      "nan\n",
      "[[ 0  1  2  3]\n",
      " [ 4  5  6  7]\n",
      " [ 8  9 10 11]]\n",
      "3\n",
      "[[99.  1. 99.  3.]\n",
      " [ 4.  5.  6. 99.]\n",
      " [ 8.  9. 10. 11.]]\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "#二维数组转置、多为数组轴滚动",
   "id": "32fcddb721a2ef36"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "de6bd8461a49a72"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
